package srg

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

var srds *redis.Client
var ctx = context.Background()

var srgHead = ""

func SetRds(rds *redis.Client) {
	srds = rds
	srgHead = fmt.Sprintf("%s%d:", "SRG", rds.Options().DB)
	defMsgQueue = srgHead + "DEF_MSG_QUEUE"
	defFlowQueue = srgHead + "DEF_FLOW_QUEUE"
	defFlowClearQueue = srgHead + "DEF_FLOW_CLEAR_QUEUE"
	delayMsgList = srgHead + "DELAY_MSG_LIST"
	queueMsgHead = srgHead + "QUEUE_MSG:"
	dLockRdsHead = srgHead + "DLOCK:"

	iniUniqueId()
}

func StartSrg() {
	go listenMsg()
	go listenFlow()
	go startDog()
}

// 注册新的消息处理
func RegisterMsgWorker(worker SrgMsgWorker) {

	srgMsgWorkers = append(srgMsgWorkers, worker)
}

// 清理数据
// 处理过期任务
func startDog() {
	var sTime int64
	var eTime int64
	time.Sleep(time.Second * 1)

	//拦截painc
	defer func() {
		if err := recover(); err != nil {
			//fmt.Println("watch dog panic", err)
		}
	}()

	for {
		locked := DLockAdd("watch_dog", time.Second*3)
		if !locked {
			fmt.Println("watch dog not get")
		}

		sTime = time.Now().UnixMilli()

		delExUniqueKey() //删除过期数据
		popQueueMsg()    //处理队列消息
		dealExMsg()      //处理往期消息
		dealExFlow()     //处理往期流程
		dealDelayMsg()   //处理延迟消息

		//处理定时任务

		eTime = time.Now().UnixMilli()
		if eTime-sTime < 2900 {
			time.Sleep(time.Duration(2900-(eTime-sTime)) * time.Millisecond)
		}
		DLockRelease("watch_dog")
		//fmt.Println("watch dog cost", eTime-sTime, "ms")

	}

}
